package model

import (
	"context"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"seckill-system/util"
	"strconv"
)

const (
	EMPTY_GIFT = 1
)

var (
	prefix = "gift_number_"
)

type GormGiftDAO struct {
	db *gorm.DB
}

func NewGormGiftDAO(db *gorm.DB) *GormGiftDAO {
	return &GormGiftDAO{
		db: db,
	}
}

var (
	_all_gift_field = util.GetGormFields(Gift{})
)

func (dao *GormGiftDAO) GetAllGifts(ctx context.Context) []*Gift {
	var gitfs []*Gift
	err := dao.db.WithContext(ctx).Select(_all_gift_field).Find(&gitfs).Error
	if err != nil {
		util.LogRus.Errorf("read table gift all gifts failed: %v", err)
	}
	return gitfs
}

func (dao *GormGiftDAO) GetAllGiftsInventory(ctx *gin.Context) []*Gift {
	client:=GetRedisClient()
	keys, err:=client.Keys(prefix+"*").Result()		//根据前缀获取所有奖品的key
	if err!=nil{
		util.LogRus.Errorf("iterate all keys by prefix %s failed: %v", prefix, err)
	}
	gifts:=make([]*Gift, 0, len(keys))
	for _, key:=range keys {
		id, err:=strconv.Atoi(key[len(prefix):])
		if err!=nil{
			util.LogRus.Errorf("invalid redis key %s", key)
			return nil
		}
		number, err:=client.Get(key).Int()
		if err!=nil{
			util.LogRus.Errorf("invalid gift inventory %s",client.Get(key).String())
			return nil
		}
		gifts = append(gifts, &Gift{
			Id: id,
			Number: number,
		})
	}
	return gifts
}



type Gift struct {
	Id     int    `gorm:"column:id; primaryKey, autoIncrement"`
	Name   string `gorm:"column:name; varchar(20)"`
	Price  int    `gorm:"column:price"`
	Number int    `gorm:"column:number"`
}
